#include "dbManager.h"

using namespace std;

DBManager* DBManager::self = nullptr;
mutex DBManager::self_mutex;

DBManager* DBManager::getInstance()
{
    if(self == nullptr) {
        self_mutex.lock();
        if(self == nullptr) {
            self = new DBManager();
        }
        self_mutex.unlock();
    }
    return self;
}

DBManager::DBManager() : sql_conn(nullptr)
{
    sql_conn = mysql_init(NULL);  //连接数据库初始化
    //连接数据库
    auto ret = mysql_real_connect(sql_conn, "127.0.0.1", "li", "031012", 
                                  "stoneBook", 3306, NULL, CLIENT_MULTI_STATEMENTS);
    if(ret == nullptr)   //连接失败
    {
        cerr << "connect mysql failed.";
    }
}

DBManager::~DBManager()
{
}

void DBManager::init()
{
    cout << "DBManager::init()\n";
}

bool DBManager::isUserExist(const std::string user)
{
    //查询用户
    string sql = "select user_name from user where user_name = '" + user + "';";
    auto search_res = mysql_query(sql_conn, sql.c_str());
    if(mysql_errno(sql_conn) != 0) {  //0成功，非0失败
        cerr << "[sql] " << sql << " [err]:" << mysql_error(sql_conn) << endl;
        return false;
    }
    auto result = mysql_store_result(sql_conn);
    int row = mysql_num_rows(result);
    return row > 0 ? true : false;
}

bool DBManager::registerUser(const std::string user, 
                    const std::string passwd, 
                    const std::string phone, 
                    const std::string email, 
                    const std::string date)
{
    string sql = "insert into user values(@user_id + 1, '" + user + "', '" + passwd + "', '" + 
                  phone + "', '" + email + "', '" + date + "');";
    auto search_res = mysql_query(sql_conn, sql.c_str());
    if(mysql_errno(sql_conn) != 0) {
        cerr << "[sql] " << sql << " [err]:" << mysql_error(sql_conn) << endl;
        return false;
    }
    return true;
}